<!-- 饼图 -->
<template>
  <div :id="id" :class="className" :style="{ height, width }" />
</template>

<script setup lang="ts">
import { nextTick, onUnmounted, onMounted } from "vue";
import { init, type EChartsOption, type EChartsType } from "echarts";
import type { RunSummary } from "./HomeView.vue";
import { useChartStore } from "@/stores/chartStore";
const props = defineProps({
  id: {
    type: String,
    default: "pieChart",
  },
  className: {
    type: String,
    default: "",
  },
  width: {
    type: String,
    default: "200px",
    required: true,
  },
  height: {
    type: String,
    default: "200px",
    required: true,
  },
  chartData: { type: Array<RunSummary>, required: true },
});

const chartStore = useChartStore();
//定义一个普通变量作为成员变量，方便各个方法调用。
let chart: EChartsType;

onMounted(() => {
  //防止div还没加载的时候就开始去进行chart的初始化，等到vue完成一个tick的HTML元素更新之后再进行操作。
  nextTick(() => {
    initChart();
  }).then(() => {
    if (chart) chartStore.listenResize(chart);
  });
});

/**
 * 完成事件的解绑
 */
onUnmounted(() => {
  if (chart) chartStore.removeListener(chart);
});

function initChart() {
  chart = init(document.getElementById(props.id) as HTMLDivElement);

  chart.setOption({
    tooltip: {
      trigger: "item",
      formatter: "{b} : {c} ",
    },
    grid: {
      left: "2%",
      right: "2%",
      bottom: "10%",
      containLabel: true,
    },

    series: [
      {
        name: "执行次数南丁格尔图",
        type: "pie",
        radius: [10, 50],
        center: ["50%", "50%"],
        roseType: "radius",
        itemStyle: {
          borderRadius: 1,
        },
        data: props.chartData.map((runSummary) => {
          return { name: runSummary.proName, value: runSummary.runTimes };
        }),
      },
    ],
  } as EChartsOption);
}
</script>

<style lang="scss" scoped></style>
